package com.cheeven.cwliu.citation.steps;

import java.io.ByteArrayInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.sax.SAXSource;
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;

public class HtmlUtil {

	Transformer transformer = null;
	static final Logger logger = Logger.getLogger(HtmlUtil.class.getName());

	public HtmlUtil() {
		try {
			transformer = TransformerFactory.newInstance().newTransformer();
		} catch (TransformerConfigurationException ex) {
			logger.log(Level.SEVERE, null, ex);
		}
	}

	public Document parseDOMDocument(String text) {
		return (Document) parseDOM(text);
	}

	public Node parseDOM(String text) {
		try {
			XMLReader reader = new Parser();
			reader.setFeature(Parser.namespacesFeature, false);
			reader.setFeature(Parser.namespacePrefixesFeature, false);

			DOMResult result = new DOMResult();
			transformer.transform(
				new SAXSource(reader,
				new InputSource(
				new ByteArrayInputStream(
				text.getBytes()))),
				result);

			return result.getNode();
		} catch (TransformerException ex) {
			logger.log(Level.SEVERE, null, ex);
		} catch (SAXNotRecognizedException ex) {
			logger.log(Level.SEVERE, null, ex);
		} catch (SAXNotSupportedException ex) {
			logger.log(Level.SEVERE, null, ex);
		}
		return null;
	}
}
